<template>
  <div>
    <br>
    <el-table :data="tableData" stripe class="tableBox">
      <el-table-column prop="cfno" label="航班号" align="center"></el-table-column>
      <el-table-column prop="startapcd" label="始发站" align="center"></el-table-column>
      <el-table-column prop="startfptt" label="预计起飞时间" align="center"></el-table-column>
      <el-table-column prop="endapcd" label="终点站" align="center"></el-table-column>
      <el-table-column prop="endfplt" label="预计到达日期" align="center"></el-table-column>
      <el-table-column label="操作" width="160" align="center">
        <template #default="scope">
          <el-button 
            :type="getButtonType(scope.row.status)" 
            plain 
            size="small" 
            @click="handleButtonClick(scope.row)">
            {{ getButtonLabel(scope.row.status) }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script setup>
import request from '@/utils/request';
import { onMounted, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const tableData = ref([]);

const gettableData = () => {
  request({
    url: '/fquery/gettickets',
    method: 'GET',
  }).then(req => {
    if (200 == req.data.errorCode) {
      tableData.value = req.data.data;
    }
  }).catch(error => {
    console.error('Error fetching data:', error);
  });
};

const getButtonLabel = (status) => {
  return status === 1 ? '退票' : '审核中';
};

const getButtonType = (status) => {
  return status === 1 ? 'info' : 'warning';
};

const handleButtonClick = (row) => {
  if (row.status === 1) {
    // Handle ticket refund
    ElMessageBox.confirm('确定要退票吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      request({
        url: '/fquery/refundTicket/' + row.id,
        method: 'POST',
      }).then(response => {
        if (response.data.errorCode == 200) {
          ElMessage({
            type: 'success',
            message: '请等待审核，审核成功后机票自动删除!',
          });
          gettableData();
        } else {
          ElMessage({
            type: 'error',
            message: response.data.message || '退票失败!',
          });
        }
      }).catch(error => {
        ElMessage({
          type: 'error',
          message: '请求失败!',
        });
        console.error('Error:', error);
      });
    }).catch(() => {
      ElMessage({
        type: 'info',
        message: '取消退票',
      });
    });
  } else if (row.status === 2) {
    // Handle review process (if needed)
    ElMessage({
      type: 'info',
      message: '审核中，无法退票',
    });
  }
};

onMounted(() => {
  gettableData();
});
</script>